package com.aistar.service.impl;

import com.aistar.mapper.DynamicMapper;
import com.aistar.pojo.Dynamic;
import com.aistar.pojo.DynamicExample;
import com.aistar.service.DynamicService;
import com.aistar.util.MessageUtil;
import com.aistar.util.ServerResponse;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class DynamicServiceImpl implements DynamicService {
    private DynamicMapper dynamicMapper;

    @Autowired
    public DynamicServiceImpl(DynamicMapper dynamicMapper) {
        this.dynamicMapper = dynamicMapper;
    }

    @Override
    public ServerResponse add(Dynamic dynamic) {
        int rows = dynamicMapper.insertSelective(dynamic);
        if (rows > 0)
            return ServerResponse.addSuccess();
        return ServerResponse.addFailed();
    }

    @Override
    public ServerResponse modify(Dynamic dynamic) {
        int rows = dynamicMapper.updateByPrimaryKeySelective(dynamic);
        if (rows > 0)
            return ServerResponse.modifySuccess();
        return ServerResponse.modifyFailed();
    }

    @Override
    public ServerResponse delete(Integer dynamicId) {
        Dynamic dynamic = new Dynamic();
        dynamic.setDynamicId(dynamicId);
        dynamic.setStatus(MessageUtil.STATUS_FAIL);
        int rows = dynamicMapper.updateByPrimaryKeySelective(dynamic);
        if (rows > 0)
            return ServerResponse.deleteSuccess();
        return ServerResponse.deleteFailed();
    }

    @Override
    public ServerResponse getById(Integer dynamicId) {
        Dynamic dynamic = dynamicMapper.selectByPrimaryKey(dynamicId);
        if (dynamic != null)
            return ServerResponse.getSuccess(dynamic);
        return ServerResponse.getFailed();
    }

    @Override
    public ServerResponse getByPage(Integer pageNum, Integer pageSize) {
        Page<Dynamic> page = PageHelper.startPage(pageNum, pageSize);
        DynamicExample example = new DynamicExample();
        example.createCriteria().andStatusEqualTo(MessageUtil.STATUS_SUCCESS);
        example.setOrderByClause("dynamic_time desc");
        List<Dynamic> dynamicList = dynamicMapper.selectByExample(example);
        if (dynamicList != null && dynamicList.size() > 0)
            return ServerResponse.getSuccess(page.toPageInfo());
        return ServerResponse.getFailed();
    }
}
